package vn.edu.uit.game_show.utilities;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;


import vn.edu.uit.chemistry.protocol.KichHoatGame;
import vn.edu.uit.chemistry.protocol.Message;
import vn.edu.uit.chemistry.protocol.ThongTinCaNhan;
import vn.edu.uit.game_show.GameActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class ClientThreadCommand implements Runnable {

	private Socket socket;
	private Thread thread;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	Context ctx;

	public ClientThreadCommand(Socket sk, Context _ctx) throws IOException {
		System.out.println("Client connected Command");
		this.socket = sk;
		this.ctx = _ctx;
	}

	public void start() throws IOException {

		oos = new ObjectOutputStream(socket.getOutputStream());
		ois = new ObjectInputStream(socket.getInputStream());

		thread = new Thread(this);
		thread.start();
		while (!thread.isAlive()) {
			//
		}

	}

	public void stop() throws IOException {

		if (socket != null) {
			socket.shutdownInput();
			socket.shutdownOutput();
			socket.close();
		}
	}

	public void run() {
		try {
			while (true) {
				handleMsg((Message) ois.readObject());
			}
		} catch (OptionalDataException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void handleMsg(Message msg) throws IOException {
		if (msg instanceof KichHoatGame) {
			kichHoatGame();
		} else if (msg instanceof ThongTinCaNhan) {
			nhanThongTinGV((ThongTinCaNhan) msg);
		} 
	}
	
	private void kichHoatGame() {
		Intent i = new Intent(ctx, GameActivity.class);
		ctx.startActivity(i);
	}
	
	private void nhanThongTinGV(ThongTinCaNhan msg){
		
		String hoten = ((ThongTinCaNhan) msg).ten;
		String msgv = ((ThongTinCaNhan) msg).mshs;
		String host = ((ThongTinCaNhan) msg).host;
		String port = ((ThongTinCaNhan) msg).port;
		
		SharedPreferences prefs = ctx.getSharedPreferences("TaiKhoanGV", 0);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString("hoten", hoten);
		editor.putString("msgv", msgv);
		editor.putString("ip", host);
		editor.putString("port", port);
		editor.commit();
	}


}
